package org.softmed.ATComm.server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;

import javax.swing.JButton;
import javax.swing.JFrame;

import org.restlet.Component;
import org.restlet.data.Protocol;
import org.softmed.ATComm.ATControlFacade;

public class RESTServer {

	protected static ATControlFacade atControl;

	public static void main(String[] args) {
		try {
			System.out.println("Starting AT Command REST Server...");
			// read configuration parameters
			// URL to bind to
			// port to bind to
			// default serial port to use
			String URL = "/atcomm";
			int port = 9802;
			String serialPort = "COM4";

			// read parameters as args fom command line
			if (args.length == 3) {
				System.out.println("Found configuration at command line");
				URL = args[0];
				port = Integer.valueOf(args[1]);
				serialPort = args[2];
			} else {
				System.out.println("No configuration found at command line.");
				System.out
						.println("Searching for configuration file \"config.txt\" ");

				File file = new File("config.txt");
				if (!file.exists()) {
					System.out
							.println("No configuration file \"config.txt\" found");
					System.out.println("Using default values.");
				} else {
					System.out.println("Found config file. Reading Values...");
					BufferedReader reader = new BufferedReader(new FileReader(
							file));

					// discard
					reader.readLine();
					URL = reader.readLine();
					reader.readLine();

					// discard
					reader.readLine();
					port = Integer.valueOf(reader.readLine());
					reader.readLine();

					// discard
					reader.readLine();
					serialPort = reader.readLine();
					reader.readLine();
				}
				System.out.println("done");
			}

			System.out.println("Configuration parameters:");
			System.out.println("URL:" + URL);
			System.out.println("PORT:" + port);
			System.out.println("SERIAL PORT:" + serialPort);

			atControl = new ATControlFacade();

			atControl.setSerialPortName(serialPort);

			Component component = new Component();

			// Add a new HTTP server listening on port
			component.getServers().add(Protocol.HTTP, port);

			ATCommApplication application = new ATCommApplication(component
					.getContext(), atControl);
			// Attach the sample application.
			component.getDefaultHost().attach(URL, application);

			System.out.println("REST Server Started OK");

			try {
				component.start();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static ATControlFacade getAtControl() {
		return atControl;
	}

}
